<template>
    <div>
        <input style="display: none" :multiple="multiple"  :id="customInput" @change="uploadFunc" type="file"/>
    <el-upload
            class="upload-demo"
            action="#"
            multiple 
            :file-list="fileList"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :disabled="disabled"  
                 
             :limit="limit"  
    >
        <el-button size="small" type="primary" @click.native.stop="uploadClick">{{mediaOnly?'选择文件':'选择图片'}}</el-button>
        <div v-if="mediaOnly" slot="tip" class="el-upload__tip">仅支持XlSX,PDF</div>
        <div v-else slot="tip" class="el-upload__tip">仅支持JPG,JPEG,PNG</div>
    </el-upload>
    </div>
</template>
<script>
    import {OSSupload,OSSDelete} from "@/utils/oss";  
    export default {
        name: 'XDUpload',
        props: {
            value: {
                type:[String,Array],
                default: ""
            },
            disabled: {
                type: Boolean,
                default: false
            },  
            limit: {
                type: Number,
                default: 9
            },
            mediaOnly: {
                type: Boolean,
                default: false
            },
             multiple: {
                type: Boolean,
                default: false
            }
        },
        data() {
            return {
                fileList: [],
                className: '',
                customInput: this.uuid()
            }
        },
        created() {
            this.init()
        },
        methods: {
            // 生成uuid
            uuid() {
                var s = [];
                var hexDigits = "0123456789abcdef";
                for (var i = 0; i < 36; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
                s[8] = s[13] = s[18] = s[23] = "-";
                var uuid = s.join("");
                return uuid;
            },
            //初始化
            init() {
                this.fileList = []
                if (this.value) {
                    if (this.value.indexOf(',') >= 0) {
                        let names = this.value.split(',')
                        for(var i=0;i<names.length;i++){
                            let name = names[i].split('-Ryan')
                            this.fileList.push({name:name, url: names[i]})
                        }
                    }else{
                        let name = this.value.split('-Ryan')
                        this.fileList.push({name: name, url: this.value})
                    }
                }  
            },
            uploadClick() {
                if (this.fileList.length == this.limit) {
                    this.handleExceed()
                    return
                }
                if (document.getElementById(this.customInput)) {
                    document.getElementById(this.customInput).value = ''
                }
                var e = document.createEvent("MouseEvents");
                e.initEvent("click", true, true);
                document.getElementById(this.customInput).dispatchEvent(e);
            },
            //上传
            uploadFunc(event) {
                console.log(event.target.files);
                const files = event.target.files;
                let name = files[0].name;
                if (this.mediaOnly) {
                    if (!this.handleExt(name)) {
                        return
                    }
                }
                for (let i=0;i<this.fileList.length;i++) {
                    if (this.fileList[i].name == name) {
                        this.$message.warning(`请勿重复上传文件${name}`);
                        return
                    }
                }
                this.fileList = [];
             
                    OSSupload(files).then((urls) => {
                        
                       console.log(urls);
                        
                        for (let i = 0; i < urls.length; i++) {
                            console.log(urls);
                           this.fileList.push({name:files[i].name,url:urls[i]}); 
                            this.$emit('change', urls[i])
                        }
        
                        this.changed()
                    }).catch(function (e) {
                        console.log(e)
                    });
            },
            //删除
            // 选择文件上传
            handleRemove(file) {
                console.log(file);
                let name = file.name;
                for (var i = 0; i < this.fileList.length; i++) {
                        if (this.fileList[i]) {
                            // if (this.fileList[i].name.indexOf(name) != -1) {
                                OSSDelete(this.fileList[i].url).then((res) => {
                                    console.log(res);
                                });
                                this.fileList.splice(i, 1);
                                this.changed()
                            // }
                        }
                }
            },
            // 发生改变
            changed() {
                var temp = ''
                for(var j=0;j<this.fileList.length;j++) {
                    j==0 ? temp += (this.fileList[j].url) : temp += (","+this.fileList[j].url)
                }
                this.$emit('input', temp)
            },
            // 超出上限
            handleExceed () {
                this.$message.warning(`上传个数已超出上限${this.limit}`);
            },
            // 支持类型
            handleExt (filename) {
              
                let supportExt = [
                    "pdf", "PDF",
                    "png", "PNG",
                    "jpg", "JPG",
                    "jpeg", "JPEG",
                    "xlsx", "XlSX",
                    "txt", "TXT"
                ] 
                if (filename.indexOf('.')>0) {
                    if (filename.split('.').length>0) {
                       let num = filename.lastIndexOf(".");
                       let dis = filename.substring(num+1,num+4);
                        if (supportExt.includes(dis)) {
                            return true
                        } else {
                            this.$message.warning(`不可识别${ext}格式, 只支持JPG,PNG,PDF,MP4格式`);
                            return false
                        }
                    }
                }else{
                    this.$message.warning(`不可识别格式, 只支持JPG,PNG,PDF,MP4格式`);
                    return false
                }
            }
        },
        watch: {
            "value": function () {
                this.init()
            }
        },
    }
</script>